package com.hfdg.prototype.base.generator;

import com.hfdg.prototype.base.annotations.Column;
import com.hfdg.prototype.base.annotations.Table;
import com.hfdg.prototype.base.utils.CamelUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.sql.JDBCType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName DatabaseInit
 * @Description TODO
 * @Author yuelh
 * @Date 2019-7-1 14:28
 * @Version 1.0
 * @Company 会飞的锅工作室
 **/
public class DatabaseInit {


    public static <T> String tableInit(Class<T> clazz) {
        {
            String tableName = clazz.getAnnotation(Table.class).name();
            if (null == tableName) {
                tableName = CamelUtils.camel2Underline(clazz.getSimpleName());
            }
            Field[] cfields = FieldUtils.getAllFields(clazz);
            List<Field> fields = new ArrayList<Field>(Arrays.asList(cfields));
            String dropSql = "drop table if exists " + tableName + ";";
            String basicSql = "create table " + tableName;
            String fieldsSql = "(";
            for (Field f : fields) {
                String fieldName = f.getName();
                Column column = f.getAnnotation(Column.class);
                String columnName = CamelUtils.camel2Underline(fieldName).toLowerCase();
                if (fieldName.equals("id")) {
                    fieldsSql += columnName + " bigint  not null  auto_increment comment '主键id',";
                } else {
                    JDBCType fieldType = column.type();
                    if (JDBCType.BIGINT == fieldType) {
                        fieldsSql += columnName + " decimal(20) default 0,";
                    } else if (JDBCType.INTEGER == fieldType) {
                        fieldsSql += columnName + " int(20) default 0,";
                    } else if (JDBCType.VARCHAR == fieldType) {
                        if (null == column) {
                            fieldsSql += columnName + " varchar(255) NULL DEFAULT NULL COMMENT '" + column.comment() + "' ,";
                        } else {
                            fieldsSql += columnName + " " + column.type() + "(" + column.length() + ") NULL DEFAULT NULL COMMENT '" + column.comment() + "' ,";
                        }
                    } else if (JDBCType.TIMESTAMP == fieldType) {
                        fieldsSql += columnName + " datetime(6) NULL DEFAULT NULL COMMENT '" + column.comment() + "' ,";
                    } else if (JDBCType.CHAR == fieldType) {
                        fieldsSql += columnName + " char(4) NULL DEFAULT NULL COMMENT '" + column.comment() + "' ,";
                    } else if (JDBCType.LONGVARCHAR == fieldType) {
                        fieldsSql += columnName + " longtext NULL DEFAULT NULL COMMENT '" + column.comment() + "' ,";
                    }
                }
            }
            fieldsSql += "primary key (id)";
            fieldsSql += ") AUTO_INCREMENT = 1 CHARACTER SET = utf8;";
            return (dropSql + basicSql + fieldsSql).toLowerCase();
        }
    }

    /**
     * Java代码实现MySQL数据库导出
     *
     * @param hostIP       MySQL数据库所在服务器地址IP
     * @param userName     进入数据库所需要的用户名
     * @param password     进入数据库所需要的密码
     * @param savePath     数据库导出文件保存路径
     * @param fileName     数据库导出文件文件名
     * @param databaseName 要导出的数据库名
     * @return 返回true表示导出成功，否则返回false。
     * @author GaoHuanjie
     */
    public static boolean exportDatabaseTool(String hostIP, String hostPort, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;

        Runtime runtime = Runtime.getRuntime();
        String path = null;
        try {
            path = ResourceUtils.getURL("classpath:sql").getPath().replace('/', '\\');
            path = path.substring(1);
            //String cmd = "mysqldump -h127.0.0.1 -uroot -P3308 -p123456 archives";
            String cmd = "C:\\Program Files\\MariaDB 10.3\\bin\\mysqldump.exe  mysqldump -h" + hostIP + " -u" + userName + " -P" + hostPort + " -p" + password + " " + databaseName;
            cmd = cmd + " > " + savePath + fileName;
            System.out.println(cmd);
            Process process = runtime.exec(cmd);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return false;
    }

    /**
     * Java实现MySQL数据库导入
     *
     * @param hostIP         MySQL数据库所在服务器地址IP
     * @param userName       数据库用户名
     * @param password       进入数据库所需要的密码
     * @param importFilePath 数据库文件路径
     * @param sqlFileName    数据库文件名
     * @param databaseName   要导入的数据库名
     * @return 返回true表示导入成功，否则返回false。
     * @author GaoHuanjie
     */
    public static boolean importDatabase(String hostIP, String hostPort, String userName, String password, String importFilePath, String sqlFileName, String databaseName) {
        File saveFile = new File(importFilePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if (!importFilePath.endsWith(File.separator)) {
            importFilePath = importFilePath + File.separator;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysql").append(" -h").append(hostIP);
        stringBuilder.append(" -u").append(userName).append(" -P").append(hostPort).append(" -p").append(password);
        stringBuilder.append(" ").append(databaseName);
        stringBuilder.append(" <").append(importFilePath).append(sqlFileName);
        try {
            Process process = Runtime.getRuntime().exec("cmd /c " + stringBuilder.toString());//必须要有“cmd /c ”
            if (process.waitFor() == 0) {// 0 表示线程正常终止。
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    //
//    public static void main(String[] args)throws IOException {
//
//        try {
//
//            if (exportDatabaseTool("127.0.0.1","3308","root","123456","D:/backupDatabase","archive-2019-01-15.sql","archives")) {
//
//                System.out.println("数据库成功备份！！！");
//
//            }else {
//
//                System.out.println("数据库备份失败！！！");
//
//            }
//
//        }catch (InterruptedException e) {
//
//            e.printStackTrace();
//
//        }
//
//        if (importDatabase("127.0.0.1","3308","root","123456","D:\\backupDatabase","archive-2019-01-15.sql","archives")) {
//
//            System.out.println("数据库导入成功！！！");
//
//        }else {
//
//            System.out.println("数据库导入失败！！！");
//
//        }
//
//        Runtime runtime = Runtime.getRuntime();
//
//        runtime.exec("mysqldump -h127.0.0.1 -uroot -P3308 -p123456 archives >d:\\123456.sql");
//
//    }
    public static void main(String[] args) throws ClassNotFoundException {
//        List<String> classes = PackageUtils.getClassName("com.hfdg.authority.entity");
//        for (String clazz : classes) {
//            String tableInitSql = tableInit(Class.forName(clazz));
//            System.out.println(tableInitSql);
//        }
        try {
            exportDatabaseTool("127.0.0.1", "3306", "root", "123456", "C:\\home\\develop\\workspace4idea\\archetype\\src\\main\\resources\\sql", "db-init.sql", "archetype");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
